package com.jetinno.simple;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.FloatRange;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.jetinno.utils.InputMethodUtil;
import com.jetinno.utils.LoadMvpView;
import com.jetinno.utils.LogUtils;
import com.jetinno.utils.ScreenUtil;
import com.jetinno.utils.SimpleCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by zhangyuncai on 2021/7/30.
 */
public abstract class SimpleDialogFragment extends DialogFragment implements LoadMvpView {
    protected String TAG = this.getClass().getSimpleName();
    protected boolean isRegisterEventBus = false;
    protected boolean hiddenSoft = false;//dialog显示后，是否隐藏键盘
    protected Context mContext;
    public FragmentActivity mActivity;
    protected View rootView;
    protected CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    protected boolean hasFetchData = false;// 标识已经触发过懒加载数据
    protected final List<SimplePresenter> presenters = new ArrayList<>();
    private DialogInterface.OnDismissListener listener;

    protected SimpleCallback sureCallback = null;
    protected SimpleCallback cancelCallback = null;

    public <T> void setSureCallback(SimpleCallback<T> sureCallback) {
        this.sureCallback = sureCallback;
    }

    public <T> void setCancelCallback(SimpleCallback<T> cancelCallback) {
        this.cancelCallback = cancelCallback;
    }

    protected void addPresenter(SimplePresenter presenter) {
        presenters.add(presenter);
    }

    @Override
    public void onAttach(Context mContext) {
        super.onAttach(mContext);
        if (mContext != null) {
            this.mContext = mContext;
        } else {
            this.mContext = getActivity();
        }
        if (this.mContext != null) {
            mActivity = (FragmentActivity) this.mContext;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutId(), container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        if (isRegisterEventBus) {
            EventBus.getDefault().register(this);
        }
        return rootView;
    }

    protected  void findViewByIds(){}

    protected <T extends View> T findViewById(@IdRes int id) {
        return rootView.findViewById(id);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Dialog dialog = getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        findViewByIds();
        if (!hasFetchData) {
            hasFetchData = true;
            initView();
            initEvent();
            initData();
        }
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initEvent();
    protected void addOnClick(int... ids) {
        for (int id : ids) {
            findViewById(id).setOnClickListener(v -> {
                onClick(v);
            });
        }
    }
    public void onClick(View v) {

    }
    protected abstract void initData();

    protected void runOnUiThread(Runnable runnable) {
        getActivity().runOnUiThread(runnable);
    }

    protected void finish() {
        dismiss();
    }

    protected void setBackClickView(View backClickView) {
        backClickView.setOnClickListener(v -> {
            finish();
        });
    }

    public void showLoadingBar(String msg) {
        if (mActivity != null && mActivity instanceof LoadMvpView) {
            ((LoadMvpView) mActivity).showLoadingBar(msg);
        }
    }

    public void dismissLoadingBar() {
        if (mActivity != null && mActivity instanceof LoadMvpView) {
            ((LoadMvpView) mActivity).dismissLoadingBar();
        }
    }

    protected void delay(long delay, SimpleCallback<Object> callback) {
        Disposable subscribe = Observable.timer(delay, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    callback.callback(true);
                }, throwable -> {
                    LogUtils.logException(TAG, throwable);
                });
        mCompositeDisposable.add(subscribe);
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        try {
            logLify("show:" + tag);
            //在每个add事务前增加一个remove事务，防止连续的add
            manager.beginTransaction().remove(this).commit();
            super.show(manager, tag);
        } catch (Exception e) {
            //同一实例使用不同的tag会异常,这里捕获一下
            LogUtils.logException(TAG, e);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        logLify("dismiss");
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        Window window = dialog.getWindow();
        if (window == null) {
            return;
        }
        //设置窗体背景色透明
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        if (hiddenSoft) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        }
        // 设置宽度为屏宽, 靠近屏幕底部。
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = getWidthStyle();
        layoutParams.height = getHeightStyle();
        layoutParams.gravity = getGravity();
        layoutParams.dimAmount = 0.8f;//设置黑暗度
        window.setAttributes(layoutParams);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (isRegisterEventBus) {
            EventBus.getDefault().unregister(this);
        }
        hasFetchData = false;
        mCompositeDisposable.dispose();
        closeKeyBoard();
        for (SimplePresenter presenter : presenters) {
            presenter.onDestory();
        }
    }

    protected void closeKeyBoard() {
        InputMethodUtil.closeKeyBoard(mActivity);
    }

    @FloatRange(from = 0.0, to = 1.0)
    protected double getWidthPercent() {
        return DialogPx.getWidthPercent();
    }

    protected int getWidthStyle() {
        double widthPercent = getWidthPercent();
        if (widthPercent > 0 && widthPercent < 1) {
            return (int) (ScreenUtil.getScreenWidth(getContext()) * widthPercent);
        }
        return WindowManager.LayoutParams.MATCH_PARENT;
    }

    @FloatRange(from = 0.0, to = 1.0)
    protected double getHeightPercent() {
        return DialogPx.getHeightPercent();
    }

    protected int getHeightStyle() {
        double heightPercent = getHeightPercent();
        if (heightPercent > 0 && heightPercent < 1) {
            return (int) (ScreenUtil.getScreenHeigth(getContext()) * heightPercent);
        }
        return WindowManager.LayoutParams.WRAP_CONTENT;
    }

    protected int getGravity() {
        return Gravity.CENTER;
    }

    public void setOnDismissListener(@Nullable DialogInterface.OnDismissListener listener) {
        this.listener = listener;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (listener != null) {
            listener.onDismiss(dialog);
        }
    }

    /**
     * 打印生命周期
     *
     * @param state
     */
    private void logLify(String state) {
        LogUtils.logOperation(TAG, state);
    }
}
